/*
 * This file is part of Shadowlands Fairways - A golf score and course info app for Android.
 *
 * Copyright (C) 2012 Jeremy D Monin <jdmonin@nand.net>.
 * Portions copyright 2009 Randall Spangler. (was Apache 2.0 licensed)
 * Portions copyright 2009 Google Inc. (was Apache 2.0 licensed)
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.shadowlands.fairways;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
//import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;


public class SettingsScreen extends Activity {
	static final int[] HOLE_CHOICES = {9, 18, 36, 54, 72};
	public static final String SAVE_FILENAME = "settings_screen.dat";

	/**
	 * Key for int preference Default Par, for android {@link SharedPreferences}.
	 * @see ScoreData#DEFAULT_PAR
	 */
	public static final String PREF_DEFAULT_PAR = "default_par";

	SeekBar mSeekPlayerCount;
	SeekBar mSeekHoleCount;
	SeekBar mSeekDefaultPar;
	CheckBox mCheckBoxLandscape;
	CheckBox mCheckBoxRelative;
	
	final ScoreData mScoreData = new ScoreData();		// Current save file
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        final TextView textPlayerCount = (TextView)findViewById(R.id.player_count);
        final TextView textHoleCount = (TextView)findViewById(R.id.hole_count);
        final TextView textDefaultPar = (TextView) findViewById(R.id.default_par);
        
        mSeekPlayerCount = (SeekBar)findViewById(R.id.seek_player_count);
        mSeekPlayerCount.setMax(7);
        mSeekPlayerCount.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
				textPlayerCount.setText(String.format("Players: %d", progress + 1));
			}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        mSeekHoleCount = (SeekBar)findViewById(R.id.seek_hole_count);
        mSeekHoleCount.setMax(HOLE_CHOICES.length - 1);
        mSeekHoleCount.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
				textHoleCount.setText(String.format("Holes: %d", HOLE_CHOICES[progress]));
			}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    
        mSeekDefaultPar = (SeekBar) findViewById(R.id.seek_default_par);
        mSeekDefaultPar.setMax(7);
        mSeekDefaultPar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
				textDefaultPar.setText(String.format("Default Par: %d", progress + 1));
			}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        mCheckBoxRelative = (CheckBox) findViewById(R.id.checkbox_scores_relative);

        mCheckBoxLandscape = (CheckBox) findViewById(R.id.checkbox_always_landscape);
        
        final Button buttonOk = (Button) findViewById(R.id.ok_button);
        buttonOk.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	/* Load the main screen's settings file.  This ensures we save only the settings
            	 * we actually can save, and don't modify the others. 
            	 */
            	loadSettings(MiniGolfScore.SAVE_FILENAME);
            	// Then save the modified settings back
            	saveSettings(MiniGolfScore.SAVE_FILENAME);
            	
            	finish();
            }
        });

        final Button buttonCancel = (Button) findViewById(R.id.cancel_button);
        buttonCancel.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	finish();
            }
        });
        
        // see onResume for further initialization.
    }

    private void loadSettings(String filename) {
    	mScoreData.loadFromFile(this, filename);
    }
    
    /**
     * Save this activity's current settings to the specified file.
     * @see MiniGolfScore#saveSettings(String)
     */
    private void saveSettings(String filename) {
    	int holes = HOLE_CHOICES[mSeekHoleCount.getProgress()];
    	int players = mSeekPlayerCount.getProgress() + 1;
    	final int par = mSeekDefaultPar.getProgress() + 1;

    	mScoreData.setDefaultPar(par);

    	mScoreData.setDimensions(players, holes);
    	
    	mScoreData.setSavedScoreRelative(mCheckBoxRelative.isChecked());

    	mScoreData.setForceLandscape(mCheckBoxLandscape.isChecked());

    	mScoreData.saveToFile(this, filename);

        // Save the Default Par to Shared Preferences,
    	// since it's not currently persisted in mScoreData.saveToFile

    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		final int oldPar = sp.getInt(PREF_DEFAULT_PAR, -1);
		if (par != oldPar)
		{
			Editor outPref = sp.edit();
			outPref.putInt(PREF_DEFAULT_PAR, par);
			outPref.commit();
		}
    }
    
	/**
	 * Activity is being paused.  It may be killed after onPause() returns.   
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
		// Log.d("MiniGolfScore.Settings", "onPause()");
		saveSettings(SAVE_FILENAME);
	}
    
    /** Activity is being resumed after pause.
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		// Log.d("MiniGolfScore.Settings", "onResume()");

		// Restore saved settings
		loadSettings(SAVE_FILENAME);
        
        mSeekPlayerCount.setProgress(mScoreData.getPlayerCount() - 1);
        
        int holes = mScoreData.getHoleCount();
        int h;
        for (h = 0; h < HOLE_CHOICES.length && holes > HOLE_CHOICES[h]; h++);
        mSeekHoleCount.setProgress(h);

        // Get the Default Par from Shared Preferences, if available.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        final int par;
        if (sp != null)
        	par = sp.getInt(PREF_DEFAULT_PAR, ScoreData.DEFAULT_PAR);
        else
        	par = ScoreData.DEFAULT_PAR;
        mSeekDefaultPar.setProgress(par - 1);

        mCheckBoxRelative.setChecked(mScoreData.getSavedScoreRelative());

        mCheckBoxLandscape.setChecked(mScoreData.getForceLandscape());
	}
    
}
    
